#!/bin/bash
#################################################################
# @Description: 用例名称：支持虚拟机资源调配控制-CPU，测试目的：支持虚拟机资源调配控制-CPU
# @Date : 2023-11-24
# @Last Modified by :
# @Last Modified time: 2023-11-27
#################################################################
source "../common.sh"
export LANG=en_US.UTF-8
res=0

vm9_name="vm9"
vm9_xml="/opt/${vm9_name}.xml"
cleanup_environment > /dev/null 2>&1

echo "启动虚拟机vm9"
virsh define $vm9_xml > /dev/null 2>&1 || { res=1; echo "$vm9_name define failed"; exit 1; }
virsh start $vm9_name > /dev/null 2>&1 || { res=1; echo "$vm9_name start failed"; exit 1; }

vnc_port9=$(virsh vncdisplay $vm9_name)
# 循环查询虚拟机的 IP 地址
echo "虚拟机VM9 启动中······"
while true; do
    ip_vm9=$(get_vm_ip "$vm9_name")
    # 如果有 IP 地址，打印信息并写入文件
    if [ -n "$ip_vm9" ]; then
        check_and_ping $ip_vm9 > /dev/null && echo "虚拟机$vm9_name IP: $ip_vm9 启动正常！" || { res=1; echo '虚拟机$vm9_name 启动失败'; }
        break  # 退出循环
    fi
    sleep 10
done

# 查询当前虚拟机vm9得调度信息
echo "1.查询当前虚拟机${vm9_name}的调度信息" 
echo "执行命令：virsh schedinfo ${vm9_name}"
virsh schedinfo ${vm9_name}
virsh schedinfo ${vm9_name} | grep 'vcpu_quota     : -1' > /dev/null 2>&1 && echo "步骤1 验证成功！" || { res=1; echo "步骤1 验证失败，脚本结束！"; exit 1; }
echo -e "\n\n"

#使用virsh命令设置虚拟机的CPU限制参数
echo "2.使用virsh命令设置虚拟机的CPU限制参数" 
echo "执行命令：virsh schedinfo ${vm9_name} --set vcpu_quota=50000"
virsh schedinfo ${vm9_name} --set vcpu_quota=50000
echo -e "\n\n"

#再次查询当前虚拟机得调度信息
echo "3.再次查询当前虚拟机得调度信息" 
echo "执行命令：virsh schedinfo ${vm9_name}"
virsh schedinfo ${vm9_name} | grep 'vcpu_quota     : 50000'
if [ $? -ne 0 ];then
	  echo "modify vcpu_quota failed."
	  exit 1
fi

#后置处理 
echo "恢复参数"
virsh schedinfo ${vm9_name} --set vcpu_quota=-1 > /dev/null 2>&1
virsh schedinfo ${vm9_name} | grep 'vcpu_quota     : -1' > /dev/null 2>&1
if [ $? -ne 0 ];then
    echo "recover vcpu_quota failed."
    exit 1
fi
# 判断用例是否执行成功
[ "$res" = "0" ] && echo -e "\033[32m-----------------test PASSED----------------\033[0m" || echo -e "\033[31m-----------------test FAILED----------------\033[0m"


